package com.example.school.utils.config;

import com.example.school.utils.common.enums.Jwt;
import com.example.school.utils.common.enums.Message;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class UserCheckToken implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String user= request.getHeader(Jwt.User_Jwt_Key.getName());
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(Jwt.User_Jwt_Key.getKey()).parseClaimsJws(user);
            Claims claims = claimsJws.getBody();
            String userId = (String) claims.get(Message.User_Id);
            BaseContext.setCurrentId(Long.valueOf(userId));
            return true;
        } catch (Exception ex) {
            response.setStatus(401);
            return false;
        }
    }
}
